import React, { useState, useEffect } from 'react';
import { getEmptySlots } from '../services/api';
import { DataTable } from '../components/SlotTable';
import { formatToBeijingTime } from '../utils/timeUtils';

const EmptySlotsPage = () => {
  const [emptySlots, setEmptySlots] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const fetchEmptySlots = async () => {
    setLoading(true);
    setError('');
    
    try {
      const data = await getEmptySlots();
      setEmptySlots(data);
    } catch (err) {
      console.error('获取无货货位失败:', err);
      setError('获取无货货位失败: ' + err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchEmptySlots();
  }, []);

  const handleRefresh = () => {
    fetchEmptySlots();
  };

  // 定义货位列配置
  const columnConfig = [
    { key: 'id', title: 'ID' },
    { key: 'layer', title: '层' },
    { key: 'row', title: '排' },
    { key: 'column', title: '列' },
    { 
      key: 'created_at', 
      title: '创建时间',
      render: (value) => formatToBeijingTime(value)
    },
    { 
      key: 'updated_at', 
      title: '更新时间',
      render: (value) => formatToBeijingTime(value)
    }
  ];

  return (
    <div style={{ padding: '20px', fontFamily: 'Arial, sans-serif' }}>
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center', 
        marginBottom: '20px' 
      }}>
        <h2>无货货位查询</h2>
        <button
          onClick={handleRefresh}
          disabled={loading}
          style={{
            padding: '8px 16px',
            backgroundColor: '#007bff',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: loading ? 'not-allowed' : 'pointer'
          }}
        >
          {loading ? '刷新中...' : '刷新'}
        </button>
      </div>
      
      <DataTable 
        data={emptySlots}
        title="无货货位列表"
        loading={loading}
        error={error}
        onRefresh={handleRefresh}
        columnConfig={columnConfig}
      />
    </div>
  );
};

export default EmptySlotsPage;